package com.dnjn.mes;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;

import java.util.concurrent.Callable;

/**
 * 启动程序
 *
 * @author dnjn
 */
@Slf4j
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, FlywayAutoConfiguration.class})
public class MesApplication {
    private static final String BIND_STOP_CALLBACK = MesApplication.class.getName() + "#APP_STOP_CALLBACK";

    private static ApplicationContext CONTEXT;

    public static void main(String[] args) throws Exception {
        if (args != null && args.length > 0 && args[0].equals("stop")) {
            Callable<?> callbabck = (Callable<?>) System.getProperties().get(BIND_STOP_CALLBACK);
            if (callbabck != null) {
                callbabck.call();
            } else {
                log.error("system couldn't start, could execute stop");
            }
        } else {
            // System.setProperty("spring.devtools.restart.enabled", "false");
            CONTEXT = SpringApplication.run(MesApplication.class, args);
            Callable<?> callable = MesApplication::stop;
            System.getProperties().put(BIND_STOP_CALLBACK, callable);//?
        }
    }

    private static Object stop() {
        if (CONTEXT != null) {
            log.info("start close..");
            int exitcode = SpringApplication.exit(CONTEXT, () -> 0);
            log.info("sys start closed {}", exitcode);
            System.exit(exitcode);
        } else {
            log.error("sys runtime evn not exists , couldn't execute stop");
        }
        return null;
    }
}
